<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button
          style="float: right"
          type="primary"
          @click="handleSearchList"
          size="s米糕"
        >
          查询搜索
        </el-button>
        <el-button
          style="float: right; margin-right: 15px"
          @click="handleResetSearch"
          size="s米糕"
        >
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form
          :inline="true"
          :model="listQuery"
          size="s米糕"
          label-width="140px"
        >
          <el-form-item label="输入搜索：">
            <el-input
              v-model="listQuery.staffName"
              class="input-width"
              placeholder="姓名"
              clearable
            ></el-input>
          </el-form-item>

          <el-form-item label="状态：">
            <el-select
              v-model="statusClass"
              clearable
              filterable
              placeholder="请选择"
            >
              <el-option label="正常" :value="0"></el-option>
              <el-option label="请假" :value="1"></el-option>
              <el-option label="离职" :value="2"></el-option>
            </el-select>
          </el-form-item>


          <el-form-item label="职责：">
            <el-select
              v-model="listQuery.post"
              clearable
              filterable
              placeholder="请选择"
            >
              <el-option label="前道" :value="0"></el-option>
              <el-option label="后道" :value="1"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="派单日期：">
            <el-date-picker
              v-model="searchAskForLeave"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"
              :default-time="['9:00:00', '23:00:00']"
              clearable
            >
              >
            </el-date-picker>
          </el-form-item>

          <el-form-item label="地区：">
            <el-select
              placeholder="市"
              clearable
              filterable
              v-model="listQuery.cityId"
            >
              <el-option
                v-for="(item, index) in areas"
                :key="index"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表(本页数量【{{list.length}}】)</span>
    </el-card>
    <div class="table-container">
      <el-table
        ref="adminTable"
        :data="list"
        style="width: 100%"
        v-loading="listLoading"
        border
      >
        <el-table-column label="姓名" align="center">
          <template slot-scope="scope">{{ scope.row.staffName }}</template>
        </el-table-column>
        <el-table-column label="地区" align="center">
          <template slot-scope="scope">{{
            scope.row.cityName || scope.row.areaName || ""
          }}</template>
        </el-table-column>

        <el-table-column label="职责" align="center">
          <template slot-scope="scope">
            {{ postOptions[scope.row.post] || "无" }}
          </template>
        </el-table-column>

        <el-table-column label="数量" align="center" sortable :sort-method="sortListByPage">
          <template slot-scope="scope">
            <!-- {{ workStatuss(scope.row.leaveStart, scope.row.leaveEnd) }} -->
           <p>{{ scope.row.num }}</p>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div
      class="pagination-container"
      style="
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        padding-bottom: 20px;
      "
    >
      <el-pagination
        background
        @current-change="handleCurrentChange"
        layout="total, prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="pageSize"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>
  <script>
import {
  getStatisticsVisitStaffVOs,
  getStatisticsVisitStaffVOsBySearch,
  getAlreadyExist,
  getUrban,
} from "@/api/staff";
import { fetchAllRoleList } from "@/api/role";
import { formatDate } from "@/utils/date";
import { maxNum, minNum } from "@/utils/max";
import rules from "./rules";
import { convertEmptyToNull } from "@/utils/null";
const defaultListQuery = {
  pageNum: 1,
  staffName: null,
  post: null,
  dispatchStart: null,
  dispatchEnd: null,
  depart: null,
  lastId: 0,
  cityId: undefined,
  isSearch: false,
  status: undefined,
};
/**
 * @param {Array<Function>} searchFunction
 */
const searchFunction = [
    getStatisticsVisitStaffVOs,
    getStatisticsVisitStaffVOsBySearch
  ]

const defaultAdmin = {
  id: null,
  staffName: null,
  depart: 1,
  status: 0,
  newPeople: 1,
  homeAddress: "",
  post: 0,
  areaId: null,
  cityId: null,
  leaveStart: "",
  leaveEnd: "",
};

const statusOptions = [
  {
    label: "正常",
    value: 0,
  },
  {
    label: "请假",
    value: 1,
  },
];

const statusOptionss = ["正常", "请假", "离职"];

const postOptions = ["前道", "后道"];


export default {
  name: "staffList",
  data() {
    return {
      statusOptionss,
      listQuery: Object.assign({}, defaultListQuery),
      list: [],
      total: 0,
      pageSize: null,
      listLoading: false,
      dialogVisible: false,
      admin: Object.assign({}, defaultAdmin),
      isEdit: false,
      allocDialogVisible: false,
      areas: [],
      normal:0,
      allocAdminId: null,
      value: "",
      statusOptions,
      newStaff: 0,
      postOptions,
      askForLeave: null,
      searchAskForLeave: null,
      rules,
      statusClass: undefined,
      status: "",
      urbanList1: [],
      urbanList2: [],
      allDagongren: [],
      allParams: {
        pageNum: 1,
        lastId: 0,
        pageSize: null,
        total: 0,
      },
      cityOptions: [],
    };
  },
  created() {
    this.getList();
    this.getAreas();
  },
  mounted() {
  },
  methods: {

    async submitAreaChange(val) {
      if (val) {
        const data = await this.getUrbans({ id: val });
        this.urbanList2 = data;
        this.admin.cityId = data[0].id;
      } else {
        this.urbanList2 = [];
        this.admin.cityId = null;
      }
    },

    sortListByPage(f, s) {
      return s.num - f.num;
    },


    //排序 倒序
    sortList() {
      this.list.length &&
        this.list.sort(function (a, b) {
          return b.num - a.num;
        });
    },

    // 弹窗关闭回调
    closed() {
      this.$refs.adminForm.clearValidate();
    },
    // 地区省份
    getAreas() {
      getAlreadyExist(this);
    },
    // 获取市区
    async getUrbans(params) {
      const res = await getUrban(params);
      return res.data || [];
    },
    handleResetSearch() {
      this.listQuery.isSearch = false;
      this.status = "";
      this.cityValue = null;
      this.listQuery = Object.assign({}, defaultListQuery);
      this.searchAskForLeave = null;
      this.getList();
    },
    handleSearchList() {

      this.listQuery.isSearch = true;

      this.listQuery.pageNum = 1;
      this.listQuery.lastId = 0;
      this.listQuery.dispatchStart = this.searchAskForLeave
        ? new Date(this.searchAskForLeave[0]).getTime() /1000
        : null;
      this.listQuery.dispatchEnd = this.searchAskForLeave
        ? new Date(this.searchAskForLeave[1]).getTime()/1000
        : null;
      /**
       *  <el-option label="正常" :value="0"></el-option>
              <el-option label="请假" :value="1"></el-option>
              <el-option label="离职" :value="2"></el-option>
       */

       let type ={
        1 : {
          key: "status",
          value: 1,
        },
        2: {
          key: "depart",
          value: 0,
        }
       };

       let value = type[this.statusClass];

       if (value) {
        this.listQuery[value['key']] = value.value;
       } else {
       this.listQuery.status = undefined;
       this.listQuery.depart = undefined;
       }

      convertEmptyToNull(this.listQuery);
      getStatisticsVisitStaffVOsBySearch(this.listQuery, this);
    },

    getList() {
      this.listLoading = true;
      getStatisticsVisitStaffVOs(this.listQuery, this);
    },

    handleSelectRole(index, row) {
      this.allocAdminId = row.id;
      this.allocDialogVisible = true;
      this.getRoleListByAdmin(row.id);
    },

    // 更新地区搜索列表
    updateCityOptions() {
      this.allParams.pageNum = 1;
      this.allParams.lastId = 0;
      this.getAllDaGongren();
    },

    getList() {
      this.listLoading = true;
      getStatisticsVisitStaffVOs(this.listQuery, this).then((response) => {
       
        this.sortList();
      });
    },
    getAllRoleList() {
      fetchAllRoleList().then((response) => {
        this.allRoleList = response.data;
      });
    },
    getRoleListByAdmin(adminId) {
      getRoleByAdmin(adminId).then((response) => {
        let allocRoleList = response.data;
        this.allocRoleIds = [];
        if (allocRoleList != null && allocRoleList.length > 0) {
          for (let i = 0; i < allocRoleList.length; i++) {
            this.allocRoleIds.push(allocRoleList[i].id);
          }
        }
      });
    },

    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
     
      searchFunction[Number(this.listQuery.isSearch)](this.listQuery, this);
    },
    handleCurrentChange(val) {
      if (val === 1) {
        this.listQuery.lastId = 0;
        searchFunction[Number(this.listQuery.isSearch)](this.listQuery, this);
      }
    }
  },

  watch: {
    askForLeave(newVal) {
      if (newVal) {
        this.admin.leaveStart = newVal[0];
        this.admin.leaveEnd = newVal[1];
      }
    },
    "listQuery.pageNum": {
      handler(newVal, oldVal) {
        if (newVal === 1) {
          this.listQuery.lastId = 0;
          return false;
        } else {
          if (newVal > oldVal && newVal === oldVal + 1) {
            this.listQuery.lastId = maxNum(this.list, "userId");
          } else if (newVal > oldVal && newVal !== oldVal + 1) {
            let num = 0;
            num =
              maxNum(this.list, "userId") +
              (newVal - oldVal - 1) * (this.pageSize || 30);
            this.listQuery.lastId = num;
          } else if (newVal < oldVal) {
            let num1 = 0;
            num1 =
              minNum(this.list, "userId") -
              1 -
              (oldVal - newVal) * (this.pageSize || 30);
            this.listQuery.lastId = num1;
          }
        }

        let index = Number(this.listQuery.isSearch);
        console.log("index", this.listQuery.isSearch);
        let func = searchFunction[index];
        func(this.listQuery, this);
      },
      deep: true,
    },
  },
  computed: {
    tooltipShow() {
      return (row) => {
        let start = new Date(row.leaveStart * 1000).getTime();
        let end = new Date(row.leaveEnd * 1000).getTime();
        let now = new Date().getTime();
        if (now < end) {
          return true;
        } else {
          return false;
        }
      };
    },
    formatDateTime() {
      return (time) => {
        if (time == null || time === "") {
          return "N/A";
        }
        let date = new Date(time);
        return formatDate(date, "yyyy/MM/dd hh:mm:ss");
      };
    },
    workStatuss() {
      return (s, e) => {
        const time = new Date().getTime() / 1000;
        if (s > 0 && e > 0) {
          if (time >= s && time <= e) {
            return "请假";
          } else {
            return "正常";
          }
        }
        return "正常";
      };
    },
  },
};
</script>
<style scoped>
.my-dialog :deep(.el-dialog) {
  min-width: 700px;
  max-width: 100%;
}
</style>
  
  
  